package com.jxwifi.cloud.quickcleanserver.mycenter;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.idroid.utils.MToast;
import com.idroid.widget.LoadDialog;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.StateUtils;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.UploadBean;
import com.jxwifi.cloud.quickcleanserver.model.AuzImpl;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.utils.Constants;
import com.jxwifi.cloud.quickcleanserver.utils.KAlertDialog;
import com.jxwifi.cloud.quickcleanserver.utils.LocationGaoDe;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;
import com.photo.PhotoPickerActivity;
import com.upload.BusinessModule;
import com.upload.ImgUpload;
import com.upload.UpLoadListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jxwifi.cloud.quickcleanserver.mycenter.AuthenticationActivity.MODE_SINGLE;

/**
 * 认证列表
 * Created by Administrator on 2020/8/5.
 */

public class HealthCertificateActivity extends CleanBasicActivity {

    private String TAG = this.getClass().getSimpleName();
    @Bind(R.id.img_health_certificate)
    ImageView img_health_certificate;
    @Bind(R.id.tv_valid_period)
    TextView tv_valid_period;
    @Bind(R.id.img_my_authentication)
    ImageView img_my_authentication;
    @Bind(R.id.tv_check)
    TextView tv_check;
    @Bind(R.id.tv_health_button)
    TextView tv_health_button;

    private static final int PICK_PHOTO = 1;
    private int authentication;//1正面 2反面
    private String mIsPositive="";//是否有上传正面 提交接口用到的数据
    private LoadDialog mLoadDialog;
    private String ucHealthCertificateJson,healthName,backImageUrl,beOverdueTime,registerTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_certificate);
        ButterKnife.bind(this);
        openEventBus();
        mLoadDialog = new LoadDialog(this,"");
        //initdata();
        initView();
    }

    private void initView() {
        ucHealthCertificateJson = getIntent().getStringExtra("ucHealthCertificateJson");
        Log.i(TAG,"onCreate ==> ucHealthCertificateJson = "+ucHealthCertificateJson);
        if(!ucHealthCertificateJson.equals("") || null == ucHealthCertificateJson){
            JSONObject json = JSON.parseObject(ucHealthCertificateJson);
            healthName = json.getString("healthName");
            backImageUrl = json.getString("backImageUrl");
            beOverdueTime = json.getString("beOverdueTime");
            registerTime = json.getString("registerTime");
            //img_my_authentication.setVisibility(View.VISIBLE);

            Log.i(TAG,"initView() ==> healthName = "+healthName);
            //健康证
        /*if(healthName.equals("wait")){
            img_my_authentication.setBackgroundResource(R.mipmap.icon_authentication_commit);
            tv_health_button.setVisibility(View.GONE);
        }else if(healthName.equals("expired")){
            img_my_authentication.setBackgroundResource(R.mipmap.icon_authentication_no);
        }else if(healthName.equals("revoked")){
            img_my_authentication.setBackgroundResource(R.mipmap.icon_authentication_no);
        }else if(healthName.equals("normal")){
            img_my_authentication.setBackgroundResource(R.mipmap.icon_authentication_wait);
            tv_health_button.setVisibility(View.GONE);
        }*/
            if(healthName.equals("")){
                tv_health_button.setVisibility(View.VISIBLE);
            }

            Glide.with(mBaseContext).load(backImageUrl).into(img_health_certificate);
            tv_valid_period.setText(beOverdueTime.split(" ")[0]);
            tv_check.setText(registerTime.split(" ")[0]);
        }

    }

    @OnClick({R.id.rel_img_back_pressed, R.id.img_health_certificate,R.id.tv_valid_period,R.id.tv_health_button,R.id.tv_check})
    void clickCK(View v){
        Intent intent = new Intent();
        switch (v.getId()){
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
            case R.id.img_health_certificate:
                initphone(1);
                break;
            case R.id.tv_valid_period:
                doChoice(1);
                break;
            case R.id.tv_check:
                doChoice(2);
                break;
            case R.id.tv_health_button:
                mLoadDialog.show();
                updateHealthAuth();
                break;
        }
    }

    /**
     * 上传健康证
     */
    public void updateHealthAuth(){
        Params params=new Params();
        params.add("registerTime",tv_check.getText().toString());
        params.add("beOverdueTime",tv_valid_period.getText().toString());
        params.add("backImageUrl",mIsPositive);
        Log.i(TAG,"updateHealthAuth ==> registerTime = "+getSysTime()+" beOverdueTime = "+tv_valid_period.getText().toString()+" backImageUrl = "+mIsPositive);
        AuzHttp.post(UrlPool.POST_UPDATE_HEALTHAU,params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code==0){
                    Log.i(TAG,"上传健康证成功");
                    mLoadDialog.dismiss();
                    tv_health_button.setVisibility(View.INVISIBLE);
                    Toast toast =Toast.makeText(mBaseContext, "提交成功", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,2000);
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Log.i(TAG,"上传健康证失败 msg = "+msg+" errorCode = "+errorCode);
                mLoadDialog.dismiss();
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        },TAG);

    }

    /**
     * 初始化界面
     */
    public void initphone(int cation){
        if (isPermissionGranted(Manifest.permission.CAMERA,
                Constants.QUEST_CODE_CAMERA)) {
            Intent intent=new Intent();
            intent.setClass(mBaseContext, PhotoPickerActivity.class);
            intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);//是否显示相机
            intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, MODE_SINGLE);//单选还是多选
            intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);//最多可选择数量
            startActivityForResult(intent, PICK_PHOTO);
            authentication=cation;
        } else {
            if (Build.VERSION.SDK_INT <= 22) {
                final KAlertDialog dialog = new KAlertDialog(mBaseContext, "相机权限已关闭\", \"相机权限已被禁止，请在设置中开启");
                dialog.setRightTxt("去查看", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //前往应用详情界面
                        try {
                            Uri packUri = Uri.parse("package:" + mBaseContext.getPackageName());
                            Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packUri);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } catch (Exception e) {
                            MToast.shortToast(mBaseContext, "跳转失败");
                        }
                        dialog.dismiss();
                    }
                });
                dialog.setLeftTxt("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        }
    }

    protected boolean isPermissionGranted(String permissionName, int questCode) {
        //6.0以下系统，取消请求权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        //判断是否需要请求允许权限，否则请求用户授权
        int hasPermision = mBaseContext.checkSelfPermission(permissionName);
        if (hasPermision != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{permissionName}, questCode);
            return false;
        }
        return true;
    }

    private String getSysTime() {
        long time = System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = new Date(time);
        String t1 = format.format(d1);
        return t1;
    }

    /**
     * 图片选择回调的方法
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PHOTO) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                Log.w("oushuhua","result"+result.get(0));
                uploadImg(result.get(0));
            }
        }
    }

    //图片上传
    public void uploadImg(String img){
        new ImgUpload(mBaseContext, UrlPool.STORAGE_UPLOAD, img, new UpLoadListener() {
            @Override
            public void onComplete(boolean isSuccess, String response) {

                if (isSuccess) {
                    UploadBean muploadbean = JSON.parseObject(response, UploadBean.class);
                    if (authentication==1){
                        Glide.with(mBaseContext).load(muploadbean.getUrl()).into(img_health_certificate);
                        mIsPositive=muploadbean.getUrl();
                    }
                } else {
                    Toaster.show(getApplicationContext(), "上传失败，请重试");
                }

            }
        }, TAG).setBusinessModule(BusinessModule.Head).doUpload();
    }

    /**
     * 选择有效期
     */
    public void doChoice(final int arg0){
        Calendar calendar1 = Calendar.getInstance();
        calendar1.add(calendar1.YEAR,1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.clear();
        TimePickerView pvtime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                if (arg0 == 2){
                    tv_check.setText(simpleDateFormat.format(date));
                }else {
                    tv_valid_period.setText(simpleDateFormat.format(date));
                }
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消")
                .setSubmitText("确定")
                .setRangDate(calendar2, calendar1)
                .setDate(calendar1)
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvtime.show();
    }


}
